package com.example.springblog.config;

import com.example.springblog.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //此处进行用户强制登陆校验
        //1.从header中获取token
        //验证token(约定前端发送请求时 header之中有key为user_token 值为token的键值对)
        String token = request.getHeader("user_token");
        log.info("从header中获取token,token:{}",token);
        Claims claims = JwtUtils.parseToken(token);
        if(claims == null){
            //token是不合法的
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
